'use strict';

const Controller = require('egg').Controller;
const Mock = require('mockjs')

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }

  async mock() {
    const { ctx, app } = this;

    const data = Mock.mock({
      "list|100-200": [{
        "img": "@image(100x100, @color)",
        name: "@cname"
      }]
    })

    // 将数据保存到数据库中
    data.list.forEach(async (item) => {
      await app.mysql.insert('list', { name: item.name, img: item.img })
    })


    ctx.body = {
      code: 1,
      msg: "请求成功"
    }
  }

  async getList() {
    const { app, ctx } = this;

    // 当前页码
    const { current } = ctx.request.body;

    // 第一页的三十条数据
    const data = await app.mysql.select("list", {
      limit: current * 30, // 数据的长度
      offset: 0

    })

    ctx.body = {
      code: 1,
      data
    }
  }

  async getDetail() {
    const { ctx, app } = this;

    const { id } = ctx.request.body;

    const data = await app.mysql.get('list', { id: id * 1 });

    ctx.body = {
      code: 1,
      data
    }
  }
}

module.exports = HomeController;
